<template>
  <div class="g-map-wrapper">
    <!-- 地图区域 -->
    <div id="g-container" :style="{ width: '100%', height: '100%' }" />
    <!-- <div class="absolute top-10 right-10">
      <el-button @click="handlePerspectiveClick" type="primary"> 切换透视 </el-button>
    </div> -->
    <template v-if="store.state.isShowControlWayline && store.state.showWaylineType === 3">
      <div class="absolute top-1/2 left-6" style="transform: translateY(-50%)">
        <div v-for="i in store.state.inclineInfo.total" :key="i" class="flex flex-col items-center">
          <div
            class="w-8 h-8 bg-[#3c3c3c] flex justify-center items-center text-white hover:bg-[#5d5f61] hover:cursor-pointer"
            :class="{ '!bg-[#2d8cf0] hover:!bg-[#5cadff]': i === store.state.inclineInfo.index }"
            @click="handleOriginInfoClick(i)"
          >
            {{ i }}
          </div>
        </div>
      </div>
      <div class="wayline-params-info-list absolute top-1/2 left-16" style="transform: translateY(-50%)">
        <div class="flex flex-col gap-3">
          <div v-for="item in store.state.inclineInfo.data" :key="item.title" class="flex flex-col items-start text-white">
            <div class="text-sm font-bold">{{ item.title }}</div>
            <div class="text-lg font-medium">{{ item.value }}</div>
          </div>
        </div>
      </div>
    </template>

    <div
      v-if="store.state.isShowControlWayline"
      class="absolute bottom-10 letf-0 right-0 w-full h-20 flex justify-center items-center gap-6 pointer-events-none"
    >
      <div class="h-full flex justify-between gap-10 items-center px-10 bg-[#00000080] text-white rounded-md pointer-events-auto">
        <template v-if="store.state.showWaylineType === 1">
          <div v-for="item in store.state.singleWaylineData" :key="item.title" class="flex flex-col items-center">
            <div class="text-sm font-bold">{{ item.title }}</div>
            <div class="text-lg font-medium">{{ item.value }}</div>
          </div>
        </template>
        <template v-if="store.state.showWaylineType === 2">
          <div v-for="item in store.state.totalWaylineData" :key="item.title" class="flex flex-col items-center">
            <div class="text-sm font-bold">{{ item.title }}</div>
            <div class="text-lg font-medium">{{ item.value }}</div>
          </div>
        </template>
        <template v-if="store.state.showWaylineType === 3">
          <div v-for="item in store.state.inclineWaylineData" :key="item.title" class="flex flex-col items-center">
            <div class="text-sm font-bold">{{ item.title }}</div>
            <div class="text-lg font-medium">{{ item.value }}</div>
          </div>
        </template>
      </div>
    </div>
    <!-- 飞机OSD -->
    <div v-if="osdVisible.visible && !osdVisible.is_dock" v-drag-window class="osd-panel fz12">
      <div class="items-center flex-row flex-justify-between h-[42px] px-4 title-header">
        <div class="drag-title flex-1">
          <span>{{ osdVisible.callsign }}</span>
        </div>
        <a class="text-sl text-white cancel min-w-12 flex justify-end" @click="() => (osdVisible.visible = false)"><X /></a>
      </div>
      <div class="flex airport-osd px-1 py-2">
        <div class="flex-column items-center flex-justify-center airport-uav !w-20">
          <a-tooltip :title="osdVisible.model">
            <div style="width: 90%" class="flex-column items-center flex-justify-center">
              <span><a-image :src="M30" :preview="false" /></span>
              <span>{{ osdVisible.model }}</span>
            </div>
          </a-tooltip>
        </div>
        <div class="osd flex-1">
          <div class="h-8 flex justify-between items-center mx-1 px-2 gap-2 title-bar">
            <div
              span="flex-1"
              :style="
                deviceInfo.device.mode_code === EModeCode.Disconnected
                  ? 'color: red; font-weight: 700;'
                  : 'color: rgb(25,190,107)'
              "
            >
              {{ EModeCodeStatus[deviceInfo.device.mode_code] }}
            </div>
            <div class="flex gap-2.5">
              <div class="h-6 button-icon"><span>视频直播</span></div>
              <div class="h-6 button-icon"><span>FPV</span></div>
            </div>
          </div>
          <div class="flex justify-between items-center mx-2 gap-2">
            <div class="h-6 flex-1 flex items-center gap-1 pl-2 item-common">
              <span>
                <Signal :size="16" />
              </span>
              <span class="ml-1 text-label">信号强度</span>
              <span>
                {{ deviceInfo.gateway?.transmission_signal_quality }}
              </span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2 item-common">
              <span> <Zap :size="16" /></span>
              <span class="text-label">遥控器电量</span>
              <span class="ml-1">{{
                deviceInfo.gateway && deviceInfo.gateway.capacity_percent !== str
                  ? deviceInfo.gateway?.capacity_percent + ' %'
                  : deviceInfo.gateway?.capacity_percent
              }}</span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2 item-common">
              <span><Zap :size="16" /></span>
              <span class="ml-1 text-label">无人机电量</span>
              <span class="ml-1">{{
                deviceInfo.device.battery.capacity_percent !== str
                  ? deviceInfo.device.battery.capacity_percent + ' %'
                  : deviceInfo.device.battery.capacity_percent
              }}</span>
            </div>
          </div>
          <div class="flex justify-between items-center mx-2 gap-2">
            <div class="h-6 flex-1 flex items-center gap-1 pl-2 item-common">
              <span>
                <img src="@/assets/icons/rtk.svg" alt="" />
              </span>
              <span class="ml-1 text-label">RTK 状态</span>
              <span
                class="ml-1 circle"
                :style="deviceInfo.device.position_state.is_fixed === 1 ? 'backgroud: rgb(25,190,107);' : ' background: red;'"
              ></span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2 item-common">
              <span><img src="@/assets/icons/rtk1.svg" alt="" /></span>
              <span class="ml-1 text-label">RTK 星数</span>
              <span class="ml-1">{{ deviceInfo.device.position_state.rtk_number }}</span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2 item-common">
              <span><img src="@/assets/icons/gps.svg" alt="" /></span>
              <span class="ml-1 text-label">GPS</span>
              <span class="ml-1">{{ deviceInfo.device.position_state.gps_number }}</span>
            </div>
          </div>
          <div class="flex justify-between items-center mx-2 gap-2">
            <div class="h-6 flex-1 flex items-center gap-1 pl-2 item-common">
              <span>
                <img src="@/assets/icons/feixingmoshi.svg" alt="" />
              </span>
              <span class="ml-1 text-label">飞行模式</span>
              <span class="ml-1">{{ EGear[deviceInfo.device.gear] }}</span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2 item-common">
              <span>
                <img src="@/assets/icons/haiba.svg" alt="" />
              </span>
              <span class="ml-1 text-label">海拔</span>
              <span class="ml-1">{{
                deviceInfo.device.height === str ? str : (+deviceInfo.device.height).toFixed(2) + ' m'
              }}</span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2 item-common">
              <span>
                <img src="@/assets/icons/flight_takeoff.svg" alt="" />
              </span>
              <span class="ml-1 text-label">起飞点高度</span>
              <span class="ml-1">{{
                deviceInfo.device.elevation === str ? str : (+deviceInfo.device.elevation).toFixed(2) + ' m'
              }}</span>
            </div>
          </div>
          <div class="flex justify-between items-center mx-2 gap-2">
            <div class="h-6 flex-1 flex items-center gap-1 pl-2 item-common">
              <span>
                <img src="@/assets/icons/jichangjuli.svg" alt="" />
              </span>
              <span class="ml-1 text-label">到机场距离</span>
              <span class="ml-1">{{
                deviceInfo.device.home_distance === str ? str : (+deviceInfo.device.home_distance).toFixed(2) + ' m'
              }}</span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2 item-common">
              <span><img src="@/assets/icons/shuipingsudu.svg" alt="" /></span>
              <span class="ml-1 text-label">水平速度</span>
              <span class="ml-1">{{
                deviceInfo.device.horizontal_speed === str ? str : (+deviceInfo.device.horizontal_speed).toFixed(2) + ' m/s'
              }}</span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2 item-common">
              <span><img src="@/assets/icons/chuizhisudu.svg" alt="" /></span>
              <span class="ml-1 text-label">垂直速度</span>
              <span class="ml-1">{{
                deviceInfo.device.vertical_speed === str ? str : (+deviceInfo.device.vertical_speed).toFixed(2) + ' m/s'
              }}</span>
            </div>
          </div>
          <div class="flex justify-between items-center mx-2 gap-2">
            <div class="h-6 flex-1 flex items-center gap-1 pl-2 item-common">
              <span><img src="@/assets/icons/wind-speed.svg" alt="" /></span>
              <span class="ml-1 text-label">风速</span>
              <span class="ml-1">{{
                deviceInfo.device.wind_speed === str ? str : (+deviceInfo.device.wind_speed / 10).toFixed(2) + ' m/s'
              }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="battery-slide" v-if="deviceInfo.device.battery.remain_flight_time !== 0">
        <div style="background: #535759" class="width-100"></div>
        <div class="capacity-percent" :style="{ width: deviceInfo.device.battery.capacity_percent + '%' }"></div>
        <div class="return-home" :style="{ width: deviceInfo.device.battery.return_home_power + '%' }"></div>
        <div class="landing" :style="{ width: deviceInfo.device.battery.landing_power + '%' }"></div>
        <div class="white-point" :style="{ left: deviceInfo.device.battery.landing_power + '%' }"></div>
        <div class="battery" :style="{ left: deviceInfo.device.battery.capacity_percent + '%' }">
          {{ Math.floor(deviceInfo.device.battery.remain_flight_time / 60) }}:
          {{ 10 > deviceInfo.device.battery.remain_flight_time % 60 ? '0' : ''
          }}{{ deviceInfo.device.battery.remain_flight_time % 60 }}
        </div>
      </div>
    </div>
    <!-- 机场OSD -->
    <div v-if="osdVisible.visible && osdVisible.is_dock" class="osd-panel fz12">
      <div class="fz16 pl5 pr5 flex-align-center flex-row flex-justify-between h-[42px] px-4 title-header">
        <div class="drag-title flex-1">
          <span>{{ osdVisible.gateway_callsign }}</span>
        </div>
        <div class="flex justify-center items-center cursor-pointer" @click="() => (osdVisible.visible = false)">
          <CloseOutlined />
        </div>
      </div>

      <!-- 机场 -->
      <div class="flex-display airport-osd px-1 pt-2">
        <div class="flex-column flex-justify-center items-stretch airport-uav">
          <a-tooltip :title="osdVisible.model">
            <div class="flex-column flex-align-center flex-justify-center" style="width: 90%">
              <span><RobotFilled style="font-size: 48px" /></span>
              <span class="mt10">机场</span>
            </div>
          </a-tooltip>
        </div>
        <div class="osd flex-1" style="flex: 1">
          <div class="h-8 flex justify-between items-center mx-1 px-2 gap-2 title-bar">
            <div
              class="flex-1"
              :style="
                deviceInfo.dock.basic_osd?.mode_code === EDockModeCode.Disconnected
                  ? 'color: red; font-weight: 700;'
                  : 'color: rgb(25,190,107)'
              "
            >
              {{ EDockModeCodeStatus[deviceInfo.dock.basic_osd?.mode_code] }}
            </div>
            <div class="flex gap-2.5">
              <el-button
                type="primary"
                size="small"
                class="!text-white"
                :style="{ backgroundColor: live.isActive ? 'green' : '' }"
                @click="openVideo(live)"
                v-for="live in dockInfo"
                :key="live.index"
              >
                {{ live.name }}
              </el-button>
              <el-button
                type="primary"
                :disabled="dockControlPanelVisible"
                size="small"
                @click="setDockControlPanelVisible(true)"
              >
                远程调试
              </el-button>
            </div>
          </div>
          <div class="flex justify-between items-center mx-2 gap-2">
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span class="flex items-center"><HistoryOutlined /></span>
              <span class="text-label">累计运行时间</span>
              <span class="ml-1">
                {{ formatAccTime(deviceInfo.dock.work_osd?.acc_time) }}
              </span>
            </div>
            <div class="h-6 flex-1 flex items-center pl-2 gap-1" style="border-radius: 2px; border: 1px solid #515151">
              <span class="flex items-center"><HistoryOutlined /></span>
              <span class="ml-1 text-label">激活时间</span>
              <span class="ml-1">
                {{ new Date((deviceInfo.dock.work_osd?.activation_time ?? 0) * 1000).toLocaleString() }}
              </span>
            </div>
          </div>
          <div class="flex justify-between items-center mx-2 gap-2">
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span :style="qualityStyle">
                <span v-if="deviceInfo.dock.basic_osd?.network_state?.type === NetworkStateTypeEnum.FOUR_G"
                  ><SignalFilled
                /></span>
                <span v-else><GlobalOutlined /></span>
              </span>
              <span class="ml-1 text-label">网络状态</span>
              <span class="ml-1">{{
                deviceInfo.dock.basic_osd?.network_state?.rate && networkSize(+deviceInfo.dock.basic_osd?.network_state?.rate)
              }}</span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/jichang.svg" alt="" />
              </span>
              <span class="ml-1 text-label">机场任务次数</span>
              <span>
                {{ deviceInfo.dock.work_osd?.job_number }}
              </span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/update.svg" alt="" />
              </span>
              <span class="ml-1 text-label">待上传数量</span>
              <span>
                {{ deviceInfo.dock.link_osd?.media_file_detail?.remain_upload }}
              </span>
            </div>
          </div>
          <div class="flex justify-between items-center mx-2 gap-2">
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/cunchu.svg" alt="" />
              </span>
              <span class="ml-1 text-label">机场存储</span>
              {{ deviceInfo.dock.basic_osd?.storage && getAirportStorage(deviceInfo.dock.basic_osd?.storage) }}
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/wind-speed.svg" alt="" />
              </span>
              <span class="ml-1 text-label">风速</span>
              <span>
                {{ (deviceInfo.dock.basic_osd?.wind_speed ?? str) + ' m/s' }}
              </span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/jiangyuliang.svg" alt="" />
              </span>
              <span class="ml-1 text-label">降雨量</span>
              <span>
                {{ RainfallStatus[deviceInfo.dock.basic_osd?.rainfall] }}
              </span>
            </div>
          </div>

          <div class="flex justify-between items-center mx-2 gap-2">
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/huanjingwendu.svg" alt="svg" />
              </span>
              <span class="ml-1 text-label">环境温度</span>
              <span class="ml-1">{{ deviceInfo.dock.basic_osd?.environment_temperature }}</span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/jichangwendu.svg" alt="" />
              </span>
              <span class="ml-1 text-label">机场温度</span>
              <span>
                {{ deviceInfo.dock.basic_osd?.environment_temperature }}
              </span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/jichangshidu.svg" alt="" />
              </span>
              <span class="ml-1 text-label">机场湿度</span>
              <span>
                {{ deviceInfo.dock.basic_osd?.humidity }}
              </span>
            </div>
          </div>
          <div class="flex justify-between items-center mx-2 gap-2">
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/gongzuodianya.svg" alt="" />
              </span>
              <span class="ml-1 text-label">工作电压</span>
              <span class="ml-1">{{ (deviceInfo.dock.work_osd?.working_voltage ?? str) + ' mV' }}</span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/gongzuodianliu.svg" alt="" />
              </span>
              <span class="ml-1 text-label">工作电流</span>
              <span>
                {{ (deviceInfo.dock.work_osd?.working_current ?? str) + ' mA' }}
              </span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/point.svg" alt="" />
              </span>
              <span class="ml-1 text-label">飞行器位置</span>
              <span>
                {{ deviceInfo.dock.basic_osd?.drone_in_dock ? '在机场' : '不在机场' }}
              </span>
            </div>
          </div>
          <!-- 机场控制面板 -->
          <DockControlPanel
            v-if="dockControlPanelVisible"
            :sn="osdVisible.gateway_sn"
            :deviceInfo="deviceInfo"
            @close-control-panel="onCloseControlPanel"
          >
          </DockControlPanel>
        </div>
      </div>
      <!--  飞机-->
      <div class="flex-display airport-osd px-1 py-2">
        <div class="flex-column flex-align-stretch flex-justify-center airport-uav">
          <a-tooltip :title="osdVisible.model">
            <div style="width: 90%" class="flex-column flex-align-center flex-justify-center">
              <span><a-image :src="M30" :preview="false" /></span>
              <span>M30</span>
            </div>
          </a-tooltip>
        </div>
        <div class="osd flex-1">
          <div class="h-8 flex justify-between items-center mx-1 px-2 gap-2 title-bar">
            <div
              class="flex-1"
              :style="
                !deviceInfo.device || deviceInfo.device?.mode_code === EModeCode.Disconnected
                  ? 'color: red; font-weight: 700;'
                  : 'color: rgb(25,190,107)'
              "
            >
              {{ !deviceInfo.device ? EModeCodeStatus[EModeCode.Disconnected] : EModeCodeStatus[deviceInfo.device?.mode_code] }}
            </div>
            <div class="flex gap-2.5" v-for="live in aircraftInfo" :key="live.index">
              <el-button
                type="primary"
                size="small"
                class="!text-white"
                :style="{ backgroundColor: live.isActive ? 'green' : '' }"
                @click="openVideo(live)"
              >
                <span>{{ live.name }}</span>
              </el-button>
            </div>
          </div>

          <div class="flex justify-between items-center mx-2 gap-2">
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/xiangshang.svg" alt="" />
              </span>
              <span class="ml-1 text-label">向上质量</span>
              <span>
                {{ deviceInfo.dock.link_osd?.sdr?.up_quality }}
              </span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/xiangxia.svg" alt="" />
              </span>
              <span class="ml-1 text-label">向下质量</span>
              <span>
                {{ deviceInfo.dock.link_osd?.sdr?.down_quality }}
              </span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/shengyudianliang.svg" alt="" />
              </span>
              <span class="ml-1 text-label">电池电量</span>
              <span class="ml-1">{{
                deviceInfo.device && deviceInfo.device.battery.capacity_percent !== str
                  ? deviceInfo.device?.battery.capacity_percent + ' %'
                  : str
              }}</span>
            </div>
          </div>
          <div class="flex justify-between items-center mx-2 gap-2">
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/rtk.svg" alt="" />
              </span>
              <span class="ml-1 text-label">RTK 状态</span>
              <span
                class="ml-1 circle"
                :style="deviceInfo.device?.position_state.is_fixed === 1 ? 'backgroud: rgb(25,190,107);' : ' background: red;'"
              ></span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span><img src="@/assets/icons/gps.svg" alt="" /></span>
              <span class="ml-1 text-label">GPS</span>
              <span class="ml-1">{{ deviceInfo.device ? deviceInfo.device.position_state.gps_number : str }}</span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span><img src="@/assets/icons/rtk1.svg" alt="" /></span>
              <span class="ml-1 text-label">RTK 星数</span>
              <span class="ml-1">{{ deviceInfo.device ? deviceInfo.device.position_state.rtk_number : str }}</span>
            </div>
          </div>
          <div class="flex justify-between items-center mx-2 gap-2">
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/feixingmoshi.svg" alt="" />
              </span>
              <span class="ml-1 text-label">飞行模式</span>
              <span class="ml-1">{{ deviceInfo.device ? EGear[deviceInfo.device?.gear] : str }}</span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/haiba.svg" alt="" />
              </span>
              <span class="ml-1 text-label">海拔</span>
              <span class="ml-1">{{
                !deviceInfo.device || deviceInfo.device.height === str ? str : (+deviceInfo.device?.height).toFixed(2) + ' m'
              }}</span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/flight_takeoff.svg" alt="" />
              </span>
              <span class="ml-1 text-label">起飞点高度</span>
              <span class="ml-1">{{
                !deviceInfo.device || deviceInfo.device.elevation === str
                  ? str
                  : (+deviceInfo.device?.elevation).toFixed(2) + ' m'
              }}</span>
            </div>
          </div>

          <div class="flex justify-between items-center mx-2 gap-2">
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span>
                <img src="@/assets/icons/jichangjuli.svg" alt="" />
              </span>
              <span class="ml-1 text-label">到机场距离</span>
              <span class="ml-1">{{
                !deviceInfo.device || deviceInfo.device.home_distance === str
                  ? str
                  : (+deviceInfo.device?.home_distance).toFixed(2) + ' m'
              }}</span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span><img src="@/assets/icons/shuipingsudu.svg" alt="" /></span>
              <span class="ml-1 text-label">水平速度</span>
              <span class="ml-1">{{
                !deviceInfo.device || deviceInfo.device?.horizontal_speed === str
                  ? str
                  : (+deviceInfo.device?.horizontal_speed).toFixed(2) + ' m/s'
              }}</span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span><img src="@/assets/icons/chuizhisudu.svg" alt="" /></span>
              <span class="ml-1 text-label">垂直速度</span>
              <span class="ml-1">{{
                !deviceInfo.device || deviceInfo.device.vertical_speed === str
                  ? str
                  : (+deviceInfo.device?.vertical_speed).toFixed(2) + ' m/s'
              }}</span>
            </div>
          </div>
          <div class="flex justify-between items-center mx-2 gap-2 pb-2">
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span><img src="@/assets/icons/wind-speed.svg" alt="" /></span>
              <span class="ml-1 text-label">风速</span>
              <span class="ml-1">{{
                !deviceInfo.device || deviceInfo.device.wind_speed === str
                  ? str
                  : (+deviceInfo.device?.wind_speed / 10).toFixed(2) + ' m/s'
              }}</span>
            </div>
            <div class="h-6 flex-1 flex items-center gap-1 pl-2" style="border-radius: 2px; border: 1px solid #515151">
              <span><img src="@/assets/icons/cunchu1.svg" alt="" /></span>
              <span class="text-label">无人机存储</span>
              {{ deviceInfo.device?.storage && getAirportStorage(deviceInfo.device?.storage) }}
            </div>
          </div>
        </div>
      </div>
      <div
        class="battery-slide"
        v-if="deviceInfo.device && deviceInfo.device.battery.remain_flight_time !== 0"
        style="border: 1px solid red"
      >
        <div style="background: #535759" class="width-100"></div>
        <div class="capacity-percent" :style="{ width: deviceInfo.device.battery.capacity_percent + '%' }"></div>
        <div class="return-home" :style="{ width: deviceInfo.device.battery.return_home_power + '%' }"></div>
        <div class="landing" :style="{ width: deviceInfo.device.battery.landing_power + '%' }"></div>
        <div class="white-point" :style="{ left: deviceInfo.device.battery.landing_power + '%' }"></div>
        <div class="battery" :style="{ left: deviceInfo.device.battery.capacity_percent + '%' }">
          {{ Math.floor(deviceInfo.device.battery.remain_flight_time / 60) }}:
          {{ 10 > deviceInfo.device.battery.remain_flight_time % 60 ? '0' : ''
          }}{{ deviceInfo.device.battery.remain_flight_time % 60 }}
        </div>
      </div>
    </div>

    <div v-if="livestreamAgoraVisibles" class="absolute right-4 bottom-4 w-[350px] z-10 flex flex-col gap-2">
      <div class="h-[234px] border border-gray-400 flex flex-col justify-center" v-for="live in openLives" :key="live.index">
        <div style="height: 30px; width: 100%; line-height: 30px; background: #535759; color: white" class="flex pl-3 pr-4 gap-3">
          <span class="flex-1">{{ live.name }}</span>

          <button @click="closeLive(live)"><X /></button>
        </div>

        <div v-if="!live.status" class="flex-1 bg-black flex justify-center items-center text-white">
          <span>暂无直播</span>
        </div>
        <div class="relative flex-1 bg-black" v-else>
          <button class="absolute top-2 right-2 z-20" @click="fullscreen(live.index)">
            <Maximize color="#fff" />
          </button>
          <div class="h-full bg-black" :id="live.index"></div>
          <!-- 移入显示操作按钮 -->
          <div
            v-if="live.types.length > 1 || !live.types.includes('normal')"
            class="absolute bottom-4 right-20 text-white border w-16 text-center border-white px-1 py-1 cursor-pointer mr-3"
            @mouseenter="live.showDetails = true"
            @mouseleave="live.showDetails = false"
          >
            {{ videoInfoType[live.type] }}
            <div
              v-if="live.showDetails"
              class="bg-black text-white p-1 text-center right-0 left-0 absolute"
              :style="{ bottom: '2rem' }"
            >
              <div
                class="py-0.5 cursor-pointer hover:bg-[#333333]"
                v-for="(typeItem, index) in live.types.filter((item) => item !== 'normal')"
                @click="handleCutAway(live, typeItem)"
                :key="index"
              >
                {{ videoInfoType[typeItem] }}
              </div>
            </div>
          </div>
          <div
            class="absolute bottom-4 right-4 text-white border w-16 text-center border-white px-1 py-1 cursor-pointer"
            @mouseenter="live.showQuality = true"
            @mouseleave="live.showQuality = false"
          >
            {{ qualityType[live.quality] }}
            <div
              v-if="live.showQuality"
              class="bg-black text-white p-1 text-center right-0 left-0 absolute"
              :style="{ bottom: '2rem' }"
            >
              <div
                class="py-0.5 cursor-pointer hover:bg-[#333333]"
                v-for="(typeItem, index) in live.qualitys"
                @click="handleQuality(live, typeItem)"
                :key="index"
              >
                {{ qualityType[typeItem] }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- <div class="h-40 border border-red-400" v-drag-window>直播开始了</div> -->
    </div>
  </div>
</template>

<script lang="ts" setup>
import { postElementsReq } from '@/api/layer'
import M30 from '@/assets/icons/m30.png'
import { MapElementEnum } from '@/constants/map'
import useGMapManage from '@/hooks/use-g-map'
import { getRoot } from '@/root'
import { useMyStore } from '@/store'

import deviceTsaUpdateHook from '@/hooks/use-model'
import {
  DeviceOsd,
  DeviceStatus,
  DockOsd,
  EDockModeCode,
  EDockModeCodeStatus,
  EGear,
  EModeCode,
  EModeCodeStatus,
  GatewayOsd,
  ILiveInfo,
  NetworkStateQualityEnum,
  NetworkStateTypeEnum,
  qualityType,
  qualityTypeKeys,
  RainfallStatus,
  videoInfoType,
  videoInfoTypeKeys
} from '@/types/device'
import { GeojsonCoordinate } from '@/types/map'
import { PostElementsBody } from '@/types/mapLayer'
import { getAirportStorage } from '@/utils/device-cmd'
import { generateLineContent, generatePointContent, generatePolyContent } from '@/utils/map-layer-utils'
import { sessionStorage } from '@/utils/storage'
import { uuidv4 } from '@/utils/uuid'
import { gcj02towgs84, wgs84togcj02 } from '@/vendors/coordtransform'
import { CloseOutlined, GlobalOutlined, HistoryOutlined, RobotFilled, SignalFilled } from '@ant-design/icons-vue'
import { debounce } from 'lodash-es'
import { Maximize, Signal, X, Zap } from 'lucide-vue-next'
import { convertTime } from 'sunrise-utils'
import { computed, reactive, ref, watch } from 'vue'
import { getLiveToken } from '../api/live'
import { getDeviceTopo, getLiveCapacity } from '../api/manage'
import useLive from '../hooks/use-live'
import { EDeviceTypeName, ELocalStorageKey } from '../types'
import { TemplateTypes, WayLineFile } from '../types/wayline'
import { parseCoordinates, processPolygonData } from '../utils/map'
import DockControlPanel from './g-map/DockControlPanel.vue'
import { useConnectMqtt } from './g-map/use-connect-mqtt'
import { useDockControl } from './g-map/use-dock-control'
const root = getRoot()

const mouseMode = ref(false)
const store = useMyStore()
const state = reactive({
  currentType: '',
  coverIndex: 0,
  isFlightArea: false
})
const str: string = '--'
const deviceInfo = reactive({
  gateway: {
    capacity_percent: str,
    transmission_signal_quality: str
  } as GatewayOsd,
  dock: {} as DockOsd,
  device: {
    gear: -1,
    mode_code: EModeCode.Disconnected,
    height: str,
    home_distance: str,
    horizontal_speed: str,
    vertical_speed: str,
    wind_speed: str,
    wind_direction: str,
    elevation: str,
    position_state: {
      gps_number: str,
      is_fixed: 0,
      rtk_number: str
    },
    storage: {
      total: 0,
      used: 0
    },
    battery: {
      capacity_percent: str,
      landing_power: str,
      remain_flight_time: 0,
      return_home_power: str
    },
    latitude: 0,
    longitude: 0
  } as DeviceOsd
})
const shareId = computed(() => {
  return store.state.layerBaseInfo.share
})
const defaultId = computed(() => {
  return store.state.layerBaseInfo.default
})
const drawVisible = computed(() => {
  return store.state.drawVisible
})
const livestreamOthersVisible = computed(() => {
  return store.state.livestreamOthersVisible
})
const livestreamAgoraVisible = computed(() => {
  return store.state.livestreamAgoraVisible
})
const osdVisible = computed(() => {
  return store.state.osdVisible
})
const qualityStyle = computed(() => {
  if (
    deviceInfo.dock.basic_osd?.network_state?.type === NetworkStateTypeEnum.ETHERNET ||
    (deviceInfo.dock.basic_osd?.network_state?.quality || 0) > NetworkStateQualityEnum.FAIR
  ) {
    return 'color: #00ee8b'
  }
  if ((deviceInfo.dock.basic_osd?.network_state?.quality || 0) === NetworkStateQualityEnum.FAIR) {
    return 'color: yellow'
  }
  return 'color: red'
})
const perspective = ref('视角跟随')
const handlePerspectiveClick = () => {
  deviceTsaUpdateHook.adjustTheAngleOfView('1231231231', `${perspective.value}`, '1231231231')
  perspective.value === '视角跟随' ? (perspective.value = '取消跟随') : (perspective.value = '视角跟随')
}
// 经纬度
onMounted(() => {
  requestAnimationFrame(() => {
    console.log(useGMapManage, 'useGMapManage')
    const data = useGMapManage.getViewer()
    console.log(data, '====')
    deviceTsaUpdateHook.init(data)
  })
})
const showDetails = ref(false)
// 直播方面的
const livestreamAgoraVisibles = computed(() => {
  return liveInfos.value.some((item) => item.isActive)
})
const closeLive = async (live: ILiveInfo) => {
  live.isActive = false
  useLive.onStop(live)
  console.log('closeVideo', live)
}
const fullscreen = (index: string) => {
  const video = document.getElementById(index) as HTMLVideoElement
  if (video) {
    if (video.requestFullscreen) {
      video.requestFullscreen()
    } else if (video.webkitRequestFullscreen) {
      video.webkitRequestFullscreen()
    } else if (video.mozRequestFullScreen) {
      video.mozRequestFullScreen()
    } else if (video.msRequestFullscreen) {
      video.msRequestFullscreen()
    }
  }
}

const handleCutAway = (live: ILiveInfo, type: videoInfoTypeKeys) => {
  useLive.onSwitchCamera(live, type)
}
// 切换清晰度
const handleQuality = (live: ILiveInfo, quality: qualityTypeKeys) => {
  useLive.onSwitchQuality(live, quality)
}
// 机场直播名称
const dockInfo = computed(() => {
  return liveInfos.value.filter((item) => item.dock)
})
// 无人机直播名称
const aircraftInfo = computed(() => {
  return liveInfos.value.filter((item) => !item.dock)
})
const liveInfos = ref<ILiveInfo[]>([
  {
    name: '相机1',
    index: '0',
    status: false,
    isActive: false,
    type: 'normal',
    types: [],
    dock: false,
    sn: '',
    client: null,
    channel: '',
    showDetails: false,
    qualitys: [0, 1, 2, 3, 4],
    quality: 0,
    showQuality: false
  }
])
// 打开直播的
const openLives = computed(() => {
  return liveInfos.value.filter((item) => item.isActive)
})
const workspaceId = ref(sessionStorage.get(ELocalStorageKey.WorkspaceId)!)
const getOnlineTopo = async () => {
  await getDeviceTopo(workspaceId.value).then((res) => {})
}
const timer = ref<NodeJS.Timeout | null>(null)
const isOpenLive = computed(() => liveInfos.value.some((item) => item.isActive))
watch(
  () => isOpenLive.value,
  async (newValue, oldValue) => {
    if (newValue) {
      startTimer()
    } else {
      stopTimer()
    }
  },
  {
    deep: true
  }
)
const stopTimer = () => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
}
onUnmounted(() => {
  stopTimer() // 页面离开时卸载定时器
})

const startTimer = () => {
  stopTimer() // 确保不会重复启动定时器
  timer.value = setInterval(async () => {
    await getOnlineTopo()
    console.log('定时器')
  }, 1000 * 60 * 5) // 每隔5分钟执行一次
}

const onRefresh = async () => {
  liveInfos.value = []
  return await getLiveCapacity({})
    .then((res) => {
      if (res.code === 1) {
        if (res.data === null) {
          console.warn('warning: get live capacity is null!!!')
          return
        }
        console.log(res.data, 'sasasasaasas')
        res.data.forEach((ele) => {
          ele.cameras_list.forEach((camera) => {
            console.log(camera, 'camera---------------')
            liveInfos.value.push({
              name: camera.name,
              index: `${ele.sn}/${camera.index}/${camera.videos_list[0].index}`,
              status: false,
              isActive: false,
              types: camera.videos_list[0].switch_video_types,
              type: camera.videos_list[0].type || 'normal',
              dock: ele.cameras_list.length === 1,
              sn: ele.sn,
              channel: `${ele.sn}_${camera.index}_${camera.videos_list[0].index}`,
              showDetails: false,
              qualitys: [0, 1, 2, 3, 4],
              quality: 0,
              showQuality: false
            })
          })
        })
      }
    })
    .catch((error) => {
      console.error(error)
    })
}
onMounted(async () => {
  onRefresh()
})
window.addEventListener('beforeunload', () => {
  liveInfos.value.forEach((item) => {
    if (item.client) {
      useLive.onStop(item)
    }
  })
})
// 直播
const openVideo = async (live: ILiveInfo) => {
  live.isActive = !live.isActive
  if (live.isActive) {
    const { data } = await getLiveToken({
      channel: live.channel
    })
    live.client = await useLive.onStart(live, {
      appId: data.appid,
      token: data.token,
      channel: live.channel
    })
  } else {
    useLive.onStop(live)
  }
}
const isDeviceOnline = ref(true)
// 在线事件使用2500ms防抖
const onlineHandler = debounce(async (data) => {
  await onRefresh()
  isDeviceOnline.value = true
  store.state.deviceStatusEvent.deviceOnline = {} as DeviceStatus
}, 2500)
// 离线事件使用50ms防抖
const offlineHandler = debounce(async (data) => {
  // deviceTsaUpdateHook.removeMarker(data.deviceOffline.sn)
  if (
    data.deviceOffline.sn === osdVisible.value.sn ||
    (osdVisible.value.is_dock && data.deviceOffline.sn === osdVisible.value.gateway_sn)
  ) {
    osdVisible.value.visible = false
    store.commit('SET_OSD_VISIBLE_INFO', osdVisible)
  }
  await onRefresh()
  console.log(data, data.deviceOffline, '====================无人机掉线=====12')
  store.state.deviceStatusEvent.deviceOffline = {} as DeviceStatus
}, 50)
// TODO: 临时注释
watch(
  () => store.state.deviceStatusEvent,
  (data) => {
    if (Object.keys(data.deviceOnline).length !== 0) {
      onlineHandler(data)
    }
    if (Object.keys(data.deviceOffline).length !== 0) {
      offlineHandler(data)
    }
  },
  {
    deep: true
  }
)

watch(
  () => store.state.deviceState,
  (data) => {
    // 网关
    if (data.currentType === EDeviceTypeName.Gateway && data.gatewayInfo[data.currentSn]) {
      const coordinate = wgs84togcj02(data.gatewayInfo[data.currentSn].longitude, data.gatewayInfo[data.currentSn].latitude)
      console.log(data.gatewayInfo[data.currentSn], '网关', coordinate)
      deviceTsaUpdateHook.moveTo(data.currentSn, coordinate[0], coordinate[1])
      if (osdVisible.value.visible && osdVisible.value.gateway_sn !== '') {
        deviceInfo.gateway = data.gatewayInfo[osdVisible.value.gateway_sn]
      }
    }
    // 无人机
    if (data.currentType === EDeviceTypeName.Aircraft && data.deviceInfo[data.currentSn]) {
      const coordinate = wgs84togcj02(data.deviceInfo[data.currentSn].longitude, data.deviceInfo[data.currentSn].latitude)
      // console.log('无人机数据', data.deviceInfo[data.currentSn], coordinate)
      const Lng = 119.40489996028663
      const Lat = 32.18677155419461
      deviceTsaUpdateHook.moveTo({
        sn: data.currentSn,
        lng: data.deviceInfo[data.currentSn].longitude === 0 ? Lng : data.deviceInfo[data.currentSn].longitude,
        lat: data.deviceInfo[data.currentSn].latitude === 0 ? Lat : data.deviceInfo[data.currentSn].latitude,
        height: +data.deviceInfo[data.currentSn].height,

        head: data.deviceInfo[data.currentSn]?.attitude_head,
        pitch: data.deviceInfo[data.currentSn]?.attitude_roll,
        roll: data.deviceInfo[data.currentSn]?.attitude_roll
      })

      // deviceTsaUpdateHook.moveTo(data.currentSn, coordinate[0], coordinate[1])
      if (osdVisible.value.visible && osdVisible.value.sn !== '') {
        deviceInfo.device = data.deviceInfo[osdVisible.value.sn]
      }
    }
    // 机场
    if (data.currentType === EDeviceTypeName.Dock && data.dockInfo[data.currentSn]) {
      const coordinate = wgs84togcj02(
        data.dockInfo[data.currentSn].basic_osd?.longitude,
        data.dockInfo[data.currentSn].basic_osd?.latitude
      )
      // console.log(
      //   '机场数据',
      //   data.dockInfo[data.currentSn],
      //   data.dockInfo[data.currentSn].basic_osd?.longitude,
      //   data.dockInfo[data.currentSn].basic_osd?.latitude
      // )

      deviceTsaUpdateHook.addAirport({
        sn: data.currentSn,
        lng: data.dockInfo[data.currentSn].basic_osd?.longitude,
        lat: data.dockInfo[data.currentSn].basic_osd?.latitude
      })
      if (osdVisible.value.visible && osdVisible.value.is_dock && osdVisible.value.gateway_sn !== '') {
        deviceInfo.dock = data.dockInfo[osdVisible.value.gateway_sn]
        deviceInfo.device = data.deviceInfo[deviceInfo.dock.basic_osd.sub_device?.device_sn ?? osdVisible.value.sn]
      }
    }
  },
  {
    deep: true
  }
)
type PointType = { Lon: number; Lat: number; height: number }

const handleOriginInfoClick = (index: number) => {
  const wayline = store.state.waylineInfo
  console.log('handleOriginInfoClick', store.state.inclinePointInfo, index, store.state.waylineInfo, '航线数据')
  const [startLat, startLon] = wayline.takeOffRefPoint.split(',')
  const startPoint = { Lon: +startLon, Lat: +startLat, height: 0 }
  handleInclineRoute(wayline, startPoint, index)
}
/**
 * 处理倾斜摄影（type 2）
 */
const handleInclineRoute = (wayline: WayLineFile<TemplateTypes[]>, startPoint: PointType, index: number) => {
  const { coordinates } = processPolygonData(wayline.templatePointInfo)
  const wayLines = wayline.inclinePointInfo[index - 1].wailinePointList!.map((point) => {
    return { ...parseCoordinates(point.Point.coordinates), height: +point.executeHeight }
  })
  wayLines.unshift(startPoint)

  // 提交额外倾斜摄影数据
  store.commit('SET_INCLINE_INFO', {
    index,
    total: Object.keys(wayline.inclinePointInfo).length,
    data: {
      distance: wayline.inclinePointInfo[index - 1].distance.toFixed(2),
      duration: convertTime(wayline.inclinePointInfo[index - 1].duration, 'en'),
      photo_num: wayline.inclinePointInfo[index - 1].photoNum
    }
  })

  useGMapManage.initPolygon(wayLines, coordinates)
}
// watch(
//   () => store.state.wsEvent,
//   (newData) => {
//     const useGMapCoverHook = useGMapCover()
//     const event = newData
//     let exist = false
//     if (Object.keys(event.mapElementCreat).length !== 0) {
//       console.log(event.mapElementCreat)
//       const ele = event.mapElementCreat
//       store.state.Layers.forEach((layer) => {
//         layer.elements.forEach((e) => {
//           if (e.id === ele.id) {
//             exist = true
//             console.log('true')
//           }
//         })
//       })
//       if (exist === false) {
//         setLayers({
//           id: ele.id,
//           name: ele.name,
//           resource: ele.resource
//         })

//         updateCoordinates('wgs84-gcj02', ele)
//         const data = { id: ele.id, name: ele.name }
//         if (MapElementEnum.PIN === ele.resource?.type) {
//           useGMapCoverHook.init2DPin(
//             ele.name,
//             ele.resource.content.geometry.coordinates,
//             ele.resource.content.properties.color,
//             data
//           )
//         } else if (MapElementEnum.LINE === ele.resource?.type) {
//           useGMapCoverHook.initPolyline(
//             ele.name,
//             ele.resource.content.geometry.coordinates,
//             ele.resource.content.properties.color,
//             data
//           )
//         } else if (MapElementEnum.POLY === ele.resource?.type) {
//           useGMapCoverHook.initPolygon(
//             ele.name,
//             ele.resource.content.geometry.coordinates,
//             ele.resource.content.properties.color,
//             data
//           )
//         }
//       }

//       store.state.wsEvent.mapElementCreat = {}
//     }
//     if (Object.keys(event.mapElementUpdate).length !== 0) {
//       console.log(event.mapElementUpdate)
//       console.log('该功能还未实现，请开发商自己增加')
//       store.state.wsEvent.mapElementUpdate = {}
//     }
//     if (Object.keys(event.mapElementDelete).length !== 0) {
//       console.log(event.mapElementDelete)
//       console.log('该功能还未实现，请开发商自己增加')
//       store.state.wsEvent.mapElementDelete = {}
//     }
//   },
//   {
//     deep: true
//   }
// )

// dock 控制面板
const { dockControlPanelVisible, setDockControlPanelVisible, onCloseControlPanel } = useDockControl()

// 连接或断开drc
useConnectMqtt()

async function postPinPositionResource(obj) {
  const req = getPinPositionResource(obj)
  setLayers(req)
  const coordinates = req.resource.content.geometry.coordinates
  updateCoordinates('gcj02-wgs84', req)
  ;(req.resource.content.geometry.coordinates as GeojsonCoordinate).push((coordinates as GeojsonCoordinate)[2])
  const result = await postElementsReq(shareId.value, req)
  obj.setExtData({ id: req.id, name: req.name })
  store.state.coverMap[req.id] = [obj]
}
async function postPolylineResource(obj) {
  const req = getPolylineResource(obj)
  setLayers(req)
  updateCoordinates('gcj02-wgs84', req)
  const result = await postElementsReq(shareId.value, req)
  obj.setExtData({ id: req.id, name: req.name })
  store.state.coverMap[req.id] = [obj]
}
async function postPolygonResource(obj) {
  const req = getPoygonResource(obj)
  setLayers(req)
  updateCoordinates('gcj02-wgs84', req)
  const result = await postElementsReq(shareId.value, req)
  obj.setExtData({ id: req.id, name: req.name })
  store.state.coverMap[req.id] = [obj]
}

function getPinPositionResource(obj) {
  const position = obj.getPosition()
  const resource = generatePointContent(position)
  const name = obj._originOpts.title
  const id = uuidv4()
  return {
    id,
    name,
    resource
  }
}
function getPolylineResource(obj) {
  const path = obj.getPath()
  const resource = generateLineContent(path)
  const { name, id } = getBaseInfo(obj._opts)
  return {
    id,
    name,
    resource
  }
}
function getPoygonResource(obj) {
  const path = obj.getPath()
  const resource = generatePolyContent(path)
  const { name, id } = getBaseInfo(obj._opts)
  return {
    id,
    name,
    resource
  }
}
function getBaseInfo(obj) {
  const name = obj.title
  const id = uuidv4()
  return { name, id }
}
function setLayers(resource: PostElementsBody) {
  const layers = store.state.Layers
  const layer = layers.find((item) => item.id.includes(shareId.value))
  // layer.id = 'private_layer' + uuidv4()
  // layer?.elements.push(resource)
  if (layer?.elements) {
    ;(layer?.elements as any[]).push(resource)
  }
  console.log('layers', layers)
  store.commit('SET_LAYER_INFO', layers)
}
function closeLivestreamOthers() {
  store.commit('SET_LIVESTREAM_OTHERS_VISIBLE', false)
}
function closeLivestreamAgora() {
  store.commit('SET_LIVESTREAM_AGORA_VISIBLE', false)
}
function updateCoordinates(transformType: string, element: any) {
  const geoType = element.resource?.content.geometry.type
  const type = element.resource?.type as number
  if (element.resource) {
    if (MapElementEnum.PIN === type) {
      const coordinates = element.resource?.content.geometry.coordinates as GeojsonCoordinate
      if (transformType === 'wgs84-gcj02') {
        const transResult = wgs84togcj02(coordinates[0], coordinates[1]) as GeojsonCoordinate
        element.resource.content.geometry.coordinates = transResult
      } else if (transformType === 'gcj02-wgs84') {
        const transResult = gcj02towgs84(coordinates[0], coordinates[1]) as GeojsonCoordinate
        element.resource.content.geometry.coordinates = transResult
      }
    } else if (MapElementEnum.LINE === type) {
      const coordinates = element.resource?.content.geometry.coordinates as GeojsonCoordinate[]
      if (transformType === 'wgs84-gcj02') {
        coordinates.forEach((coordinate, i, arr) => {
          arr[i] = wgs84togcj02(coordinate[0], coordinate[1]) as GeojsonCoordinate
        })
      } else if (transformType === 'gcj02-wgs84') {
        coordinates.forEach((coordinate, i, arr) => {
          arr[i] = gcj02towgs84(coordinate[0], coordinate[1]) as GeojsonCoordinate
        })
      }
      element.resource.content.geometry.coordinates = coordinates
    } else if (MapElementEnum.POLY === type) {
      const coordinates = element.resource?.content.geometry.coordinates[0] as GeojsonCoordinate[]
      if (transformType === 'wgs84-gcj02') {
        coordinates.forEach((coordinate, i, arr) => {
          arr[i] = wgs84togcj02(coordinate[0], coordinate[1]) as GeojsonCoordinate
        })
      } else if (transformType === 'gcj02-wgs84') {
        coordinates.forEach((coordinate, i, arr) => {
          arr[i] = gcj02towgs84(coordinate[0], coordinate[1]) as GeojsonCoordinate
        })
      }
      element.resource.content.geometry.coordinates = [coordinates]
    }
  }
}
// 换算网络大小
const networkSize = (quality: number) => {
  let size: string
  let unit: string

  if (quality < 1024) {
    size = quality.toFixed(2)
    unit = 'KB/s'
  } else if (quality > 1024 && quality < 1048576) {
    size = (quality / 1024).toFixed(2)
    unit = 'MB/s'
  } else {
    size = (quality / 1024 / 1024).toFixed(2)
    unit = 'GB/s'
  }

  return `${size} ${unit}`
}
// 计算运行时间
const formatAccTime = (accTime: number): string => {
  const months = Math.floor(accTime / 2592000)
  const days = Math.floor((accTime % 2592000) / 86400)
  const hours = Math.floor(((accTime % 2592000) % 86400) / 3600)
  const minutes = Math.floor((((accTime % 2592000) % 86400) % 3600) / 60)
  const seconds = Math.floor((((accTime % 2592000) % 86400) % 3600) % 60)

  let result = ''
  if (months > 0) {
    result += `${months}月`
  }
  if (days > 0) {
    result += `${days}天`
  }
  if (hours > 0) {
    result += `${hours}时`
  }
  if (minutes > 0) {
    result += `${minutes}分`
  }
  if (seconds > 0) {
    result += `${seconds}秒`
  }
  return result.trim()
}
const isFirstView = ref(false)
</script>

<style lang="scss" scoped>
.g-map-wrapper {
  height: 100%;
  width: 100%;

  .g-action-panel {
    position: absolute;
    top: 16px;
    right: 16px;
    .g-action-item {
      width: 28px;
      height: 28px;
      background: white;
      color: $primary;
      border-radius: 2px;
      line-height: 28px;
      text-align: center;
      margin-bottom: 2px;
    }
    .g-action-item:hover {
      border: 1px solid $primary;
      border-radius: 2px;
    }
  }
  .selection {
    border: 1px solid $primary;
    border-radius: 2px;
  }

  // antd button 光晕
  &:deep(.ant-btn) {
    &::after {
      display: none;
    }
  }
}
.osd-panel {
  position: absolute;
  margin-left: 10px;
  left: 0;
  top: 10px;
  // width: vw(588);
  width: vw(660);
  background: rgba(48, 48, 48, 0.95);
  color: #fff;
  border-radius: 2px;
  .title-header {
    background-color: rgba(0, 0, 1, 0.4);
  }
}
.osd > div:not(.title-bar) {
  margin-top: 5px;
  padding-left: 5px;
}

.circle {
  border-radius: 50%;
  width: 10px;
  height: 10px;
}

.battery-slide {
  .capacity-percent {
    background: #00ee8b;
  }
  .return-home {
    background: #ff9f0a;
  }
  .landing {
    background: #f5222d;
  }
  .white-point {
    width: 4px;
    height: 4px;
    border-radius: 50%;
    background: white;
    bottom: -0.5px;
  }
  .battery {
    background: #141414;
    color: #00ee8b;
    margin-top: -10px;
    height: 20px;
    width: auto;
    border-left: 1px solid #00ee8b;
    padding: 0 5px;
  }
}
.battery-slide > div {
  position: absolute;
  min-height: 2px;
  border-radius: 2px;
}

.liveview {
  position: absolute;
  color: #fff;
  z-index: 1;
  left: 0;
  margin-left: 10px;
  top: 10px;
  text-align: center;
  width: 800px;
  height: 720px;
  background: #232323;
}
.button-icon {
  // background-image: url('@/assets/icons/button.svg');
  // background-size: auto;
  text-align: center;
  cursor: pointer;
  // width: vw(76);
  padding: 0px vw(10);
  // height: vh(28);
  background: linear-gradient(#4065fd, #0e171e 50%, #509cfe);
  border-radius: 1.5px;
  opacity: 0.65;
  border: 1px solid #509cfe;
  &:hover {
    opacity: 1;
    background: linear-gradient(#509cfe, #0e171e 50%, #4065fd);
    border: 1px solid #4065fd;
  }
  span {
    font-size: px2font(14);
    font-weight: 400;
    text-align: left;
    color: rgab(0, 0, 0, 0.65);
  }
}
.text-label {
  font-size: px2font(14);
  font-weight: 400;
  color: rgba(225, 225, 225, 0.65);
}
.title-bar {
  background-color: rgba(0, 0, 1, 0.4);
}

.airport-uav {
  width: vw(60);
  background-color: rgba(0, 0, 1, 0.4);
}
.item-common {
  border-radius: 2px;
  border: 1px solid #515151;
}
</style>
